<template>
    <div>
        <el-card class="card">
            <div class="title">
                <h2 style="text-align: center">角色管理</h2>
            </div>
        </el-card>
        <br />
        <el-card>
            <el-row>
                <el-col :span="4">
                    <el-input v-model="roleName" clearable><template slot="prepend">名称：</template></el-input>
                </el-col>
                <el-col :span="1" style="margin-left: 5px">
                    <el-button type="primary" @click="search">查询</el-button>
                </el-col>
                <el-col :span="1" :offset="1">
                    <el-button type="info" style="margin-bottom: 5px" @click="addDialog">新增角色</el-button>
                </el-col>
            </el-row>
            <div>
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column prop="roleName" label="名称" header-align="center" align="center"> </el-table-column>
                    <el-table-column prop="description" label="描述" header-align="center" align="center"> </el-table-column>
                    <el-table-column label="操作" header-align="center" align="center">
                        <template slot-scope="scope">
                            <el-button type="primary" @click="editRoleById(scope.row.id)">编辑</el-button>
                            <el-button type="danger" @click="deleteRoleById(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <br />
                <!--分页部分-->
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageInfo.pageNum"
                    :page-sizes="[10, 15, 20, 25]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageInfo.total"
                >
                </el-pagination>
            </div>
        </el-card>
        <!--新增角色对话框-->
        <el-dialog title="新增" :close-on-click-modal="false" :visible.sync="addDialogVisible">
            <el-form :model="addRoleForm" :rules="dataRule" ref="addRoleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input v-model="addRoleForm.description" placeholder="备注"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="授权">
                    <el-tree
                        :data="menuList"
                        :props="menuListTreeProps"
                        node-key="menuId"
                        ref="menuListTree"
                        :default-expand-all="true"
                        show-checkbox
                    >
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="pushAddRole">确定</el-button>
            </span>
        </el-dialog>
        <!--编辑角色对话框-->
        <el-dialog title="修改" :close-on-click-modal="false" :visible.sync="editDialogVisible">
            <el-form :model="editRoleForm" :rules="dataRule" ref="editRoleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="description">
                    <el-input v-model="editRoleForm.description" placeholder="备注"></el-input>
                </el-form-item>
                <el-form-item size="mini" label="授权">
                    <el-tree
                        :data="menuList"
                        :props="menuListTreeProps"
                        node-key="menuId"
                        ref="menuListTree"
                        :default-expand-all="true"
                        show-checkbox
                    >
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEditRole">取消</el-button>
                <el-button type="primary" @click="pushEditRole">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import roleApi from '../../../api/role';
import { treeDataTranslate } from '@/utils';
import permissionApi from '../../../api/permission';
export default {
    data() {
        return {
            tableData: [],
            addDialogVisible: false,
            addRoleForm: {},
            permissionOptions: [],
            pageInfo: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            roleName: '',
            editDialogVisible: false,
            editRoleForm: {},
            dataRule: {
                roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
            },
            menuList: [],
            menuListTreeProps: {
                label: 'name',
                children: 'children'
            },
            tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
        };
    },
    methods: {
        handleSizeChange(val) {
            this.pageInfo.pageSize = val;
            this.getRoleData();
        },
        // 分页函数
        handleCurrentChange(current) {
            this.pageInfo.pageNum = current;
            this.getRoleData();
        },
        async getPermissions() {
            await roleApi.getPermisions().then((res) => {
                console.log(res.data);
                for (let i = 0; i < res.data.length; ++i) {
                    this.permissionOptions[i] = {
                        value: res.data[i].menuId,
                        label: res.data[i].name
                    };
                }
                // 强制刷新 解决有数据不渲染的问题
                this.$forceUpdate();
            });
        },
        // 查询
        async search() {
            await roleApi.getByName(this.roleName).then((res) => {
                this.tableData = res.data;
            });
        },
        addDialog() {
            permissionApi.getAll().then((res) => {
                this.menuList = treeDataTranslate(res.data, 'menuId');
            });
            this.addDialogVisible = true;
            this.$nextTick(() => {
                this.$refs['addRoleForm'].resetFields();
                this.$refs.menuListTree.setCheckedKeys([]);
            });
            this.addRoleForm = {};
        },
        async getRoleData() {
            await roleApi.getAll().then((res) => {
                this.pageInfo.total = res.data.length;
            });
            await roleApi.getRoleByPage(this.pageInfo.pageNum, this.pageInfo.pageSize).then((res) => {
                console.log(res.data);
                this.tableData = res.data;
            });
        },
        // 新增
        async pushAddRole() {
            var data = {
                roleName: this.addRoleForm.roleName,
                description: this.addRoleForm.description,
                menuIdList: [].concat(
                    this.$refs.menuListTree.getCheckedKeys(),
                    [this.tempKey],
                    this.$refs.menuListTree.getHalfCheckedKeys()
                )
            };
            await roleApi.addRole(data).then((res) => {
                console.log(res);
                if (res.success == true) {
                    this.$message({
                        message: '添加角色成功！',
                        type: 'success'
                    });
                } else {
                    this.$notify.error({
                        title: '操作错误',
                        message: res.message,
                        duration: 0
                    });
                }
                this.getRoleData();
                this.$forceUpdate();
                this.addDialogVisible = false;
            });
        },
        editRoleById(id) {
            permissionApi.getAll().then((res) => {
                this.menuList = treeDataTranslate(res.data, 'menuId');
            });
            this.editDialogVisible = true;
            this.$nextTick(() => {
                this.$refs['editRoleForm'].resetFields();
                this.$refs.menuListTree.setCheckedKeys([]);
            });
            roleApi.getRoleById(id).then((res) => {
                console.log(res.data);
                this.editRoleForm = res.data;
                var idx = res.data.menuIdList.indexOf(this.tempKey);
                if (idx != -1) {
                    res.data.menuIdList.splice(idx, res.data.menuIdList.length - idx);
                }
                this.$refs.menuListTree.setCheckedKeys(res.data.menuIdList);
            });
        },
        // 取消编辑
        cancelEditRole() {
            this.editDialogVisible = false;
            this.$refs['editRoleForm'].resetFields();
            this.$refs.menuListTree.setCheckedKeys([]);
        },
        // 提交编辑
        async pushEditRole() {
            var data = {
                roleName: this.editRoleForm.roleName,
                description: this.editRoleForm.description,
                menuIdList: [].concat(
                    this.$refs.menuListTree.getCheckedKeys(),
                    [this.tempKey],
                    this.$refs.menuListTree.getHalfCheckedKeys()
                )
            };
            await roleApi.editRole(this.editRoleForm.id, data).then((res) => {
                console.log(res);
                if (res.success == true) {
                    this.$message({
                        message: '修改成功！',
                        type: 'success'
                    });
                } else {
                    this.$notify.error({
                        title: '操作错误',
                        message: res.message,
                        duration: 0
                    });
                }
                this.getRoleData();
                this.$forceUpdate();
                this.editDialogVisible = false;
            });
        },
        async deleteRoleById(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该项目, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((err) => err);
            if (confirmResult != 'confirm') {
                return;
            }
            if (confirmResult == 'confirm') {
                await roleApi.deleteRole(id).then((res) => {
                    this.$message({
                        message: '删除成功！',
                        type: 'success'
                    });
                    this.getRoleData();
                });
            }
        }
    },
    created() {
        this.getRoleData();
        this.getPermissions();
    }
};
</script>

<style>
</style>
